I'm attempting to add an event listener to the document element, which remains active only while a specific section element is within the visible portion of the viewport.
This listener listens for two keypresses, ArrowLeft and ArrowRight, and calls matching functions moveLeft() and moveRight() for each case. Once the section is no longer visible within the viewport the eventListener is to be removed.
const cObserverHandler = entries => {
const [entry] = entries;
const keyListener = e => {
if (e.key === 'ArrowLeft') moveLeft();
else if (e.key === 'ArrowRight') moveRight();
};
if (entry.isIntersecting) {
console.log('intersect');
document.addEventListener('keyup', keyListener);
} else if (!entry.isIntersecting) {
console.log('depart');
document.removeEventListener('keyup', keyListener);
}
};
For brevity I've excluded the IntesectionObserver setup and larger app functioning.
As well, to those not already familiar, within this context entry.isIntersecting will evaluate to a Boolean value based on whether the aforementioned section is within the visible area of the viewport.
El problema:
Examining the console, the messages 'intersect' and 'depart' fire during my scroll testing at the expected times. However, some further stress-testing has shown that arrow presses are being registered and acted on even after the point at which the listener should be removed. Any thoughts on why this might be?
Thanks for reading.